package com.zidian.study.adapter;

import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.study.bean.QuestionDetailBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zidian.student.trucks.R;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zidian.study.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/8/24 0024.
 * 提问详情适配器
 */
public class InteractionDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_FOOTER = 1;
    private static final int TYPE_Head = 2;
    private Context context;
    private List<QuestionDetailBean.DataBean.AnswerBean> data;
    private QuestionDetailBean.DataBean.IssueBean question =
            new QuestionDetailBean.DataBean.IssueBean();
    private static boolean hasMore = true;
    private int Total;
    private int questionType;

    public InteractionDetailAdapter(Context context,
                                    List<QuestionDetailBean.DataBean.AnswerBean> data) {
        this.context = context;
        this.data = data;
    }

    /**
     * 设置问题
     */
    public void setQuestion(QuestionDetailBean.DataBean.IssueBean question) {
        this.question = question;
    }

    /**
     * 设置问题类型（0表示还可以添加回答，1表示已经采纳，不可添加回答）
     *
     * @param questionType
     */
    public void setQuestionType(int questionType) {
        this.questionType = questionType;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    public void setTotal(int total) {
        this.Total = total;
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    @Override
    public int getItemCount() {
        return data.size() + 2;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else if (position == 0) {
            return TYPE_Head;
        } else {
            return TYPE_ITEM;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view =
                    LayoutInflater.from(context).inflate(R.layout.item_interaction_ask_req, parent, false);
            return new ItemViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View view =
                    LayoutInflater.from(context).inflate(R.layout.item_interaction_ask_foot, parent, false);
            return new FootViewHolder(view);
        } else if (viewType == TYPE_Head) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_ask_detil_top, parent, false);
            return new HeadViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder,  int position) {
        if (holder instanceof ItemViewHolder) {
            if (questionType == 0) {//TODO 问题尚未采纳，还可以采纳回答
                if (question.getIssueType() == 1) {//如果不是自己的提问就无法采纳
                    //如果是本人的回答则无法被采纳
                    if (question.getIssuePersonId().equals(data.get(position - 1).getAnswerPersonId())) {
                        ((ItemViewHolder) holder).answerAccept.setVisibility(View.GONE);
                    } else {
                        ((ItemViewHolder) holder).answerAccept.setVisibility(View.VISIBLE);
                    }
                } else {
                    //显示已经被采纳的回答
                    if (data.get(position - 1).getAnswerType() == 1) {
                        ((ItemViewHolder) holder).answerAccept.setVisibility(View.VISIBLE);
                        ((ItemViewHolder) holder).answerAccept.setImageResource(R.drawable.answer_accepted);
                    } else {
                        ((ItemViewHolder) holder).answerAccept.setVisibility(View.GONE);
                    }
                }
                ((ItemViewHolder) holder).answerAccept.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        acceptAnswer(data.get(holder.getAdapterPosition() - 1).getAnswerId()
                                , question.getIssueId(), data.get(holder.getAdapterPosition() - 1).getAnswerPersonId());
                    }
                });

            } else if (questionType == 1) {//TODO  问题已经采纳，无法继续采纳回答
                if (data.get(position - 1).getAnswerType() == 1) {
                    ((ItemViewHolder) holder).answerAccept.setVisibility(View.VISIBLE);
                    ((ItemViewHolder) holder).answerAccept.setImageResource(R.drawable.answer_accepted);
                } else {//
                    ((ItemViewHolder) holder).answerAccept.setVisibility(View.GONE);
                }
            }

            if (data.get(position - 1).getAnswerTime() != null) {
                ((ItemViewHolder) holder).answerName.setText(data.get(position - 1).getAnswerPersonName());
                ((ItemViewHolder) holder).answerTime.setText(data.get(position - 1).getAnswerTime());
                ((ItemViewHolder) holder).answerContent.setText(data.get(position - 1).getAnswerText());

                Glide.with(context)
                        .load(data.get(position - 1).getAnswerUrl())
                        .fitCenter()
                        .into(((ItemViewHolder) holder).answerImage);
                Glide.with(context)
                        .load(data.get(position - 1).getAnswerHeadPortrait())
                        .placeholder(R.mipmap.quiz)
                        .centerCrop()
                        .into(((ItemViewHolder) holder).userImage);
            }

            if (onItemClickListener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = holder.getLayoutPosition();
                        onItemClickListener.onItemClick(holder.itemView, position);
                    }
                });

                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int position = holder.getLayoutPosition();
                        onItemClickListener.onItemLongClick(holder.itemView, position);
                        return false;
                    }
                });
            }
        } else if (holder instanceof FootViewHolder) {
            if (!hasMore) {
                ((FootViewHolder) holder).loadText.setText("全部数据加载完成!");
                ((FootViewHolder) holder).progressBar.setVisibility(View.GONE);
            } else {
                ((FootViewHolder) holder).loadText.setText("正在加载...");
                ((FootViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
            }
        } else if (holder instanceof HeadViewHolder) {
            if (question.getIssueTime() != null) {
                ((HeadViewHolder) holder).issueClass.setText(question.getIssueObject());
                ((HeadViewHolder) holder).issueContent.setText(question.getIssueText());
                ((HeadViewHolder) holder).issueName.setText(question.getIssuePersonName());
                ((HeadViewHolder) holder).issueTime.setText(dateToStamp(question.getIssueTime()));
                if (question.getIssueUrl() != null) {
                    ((HeadViewHolder) holder).issueImage.setVisibility(View.VISIBLE);
                } else {
                    ((HeadViewHolder) holder).issueImage.setVisibility(View.GONE);
                }
                if (question.getIssueUrl().size() > 0) {
                    Glide.with(context)
                            .load(question.getIssueUrl().get(0).getUrl())
                            .fitCenter()
                            .into(((HeadViewHolder) holder).issueImage);
                } else {
                    ((HeadViewHolder) holder).issueImage.setVisibility(View.GONE);
                }
                Glide.with(context)
                        .load(question.getIssuePersonHeadPortrait())
                        .placeholder(R.mipmap.quiz)
                        .centerCrop()
                        .into(((HeadViewHolder) holder).userImage);
            }
            ((HeadViewHolder) holder).issueTotal.setText(Total + "");
        }
    }

    /**
     * 采纳回答
     * @param answerId
     * @param issueId
     * @param answerPersonId
     */
    private void acceptAnswer( String answerId, String issueId, String answerPersonId) {
        String url = Constant.URL_GOAL + "issueStudent/addAnswerIssue";
        Map<String, String> map = new HashMap<>();
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("answerId", answerId);
        map.put("issueId", issueId);
        map.put("answerPersonId", answerPersonId);
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(context);
        OkHttpUtils.post()
                .url(url)
                .params(map)
                .build()
                .execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast(context , "采纳失败");
                ProgressBarBlackUtil.loadCancel();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 200) {
                        ToastUtil.showToast(context, "采纳成功");
                        questionType = 1;
                        notifyDataSetChanged();
                    } else {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        ImageView userImage;
        ImageView answerImage;
        TextView answerName;
        TextView answerTime;
        TextView answerContent;
        ImageView answerAccept;

        public ItemViewHolder(View view) {
            super(view);
            userImage = (ImageView) view.findViewById(R.id.answer_user_image);
            answerImage = (ImageView) view.findViewById(R.id.answer_image);
            answerName = (TextView) view.findViewById(R.id.answer_name);
            answerTime = (TextView) view.findViewById(R.id.answer_time);
            answerContent = (TextView) view.findViewById(R.id.answer_content);
            answerAccept = (ImageView) view.findViewById(R.id.accept_iv);
        }
    }

    static class FootViewHolder extends RecyclerView.ViewHolder {
        TextView loadText;
        ProgressBar progressBar;

        public FootViewHolder(View view) {
            super(view);
            loadText = (TextView) view.findViewById(R.id.load_text);
            progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        }
    }

    static class HeadViewHolder extends RecyclerView.ViewHolder {
        ImageView userImage;
        ImageView issueImage;
        TextView issueClass;
        TextView issueTime;
        TextView issueContent;
        TextView issueTotal;
        TextView issueName;

        public HeadViewHolder(View view) {
            super(view);
            userImage = (ImageView) view.findViewById(R.id.ask_issue_image);
            issueImage = (ImageView) view.findViewById(R.id.question_image);
            issueClass = (TextView) view.findViewById(R.id.ask_issue_class);
            issueTime = (TextView) view.findViewById(R.id.ask_issue_time);
            issueContent = (TextView) view.findViewById(R.id.ask_issue_cotent);
            issueTotal = (TextView) view.findViewById(R.id.ask_issue_total);
            issueName = (TextView) view.findViewById(R.id.ask_issue_name);
        }
    }

    public static String dateToStamp(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        res = simpleDateFormat.format(new Date(Long.parseLong(String.valueOf(s))));
        return res;
    }
}
